import React, { useEffect, useState } from "react";
import { Modal, Form, Row, Col, InputNumber, Space, Button, Input } from "antd";
import { inWarehouseType, modalPropsType } from "@/constants/types";
import { MinusOutlined, PlusOutlined } from "@ant-design/icons";
import "./index.less";
import { inWhVerifyData, calcInWhVerifyData } from "../../services";
import { isEmptyObj } from "@/utils/util";

const { Item } = Form;
const rules = [{required: true, message: '此项必填'}];

const WarehouseEntryExport = ({visible, onCancel, onSubmit, title, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const [info, setInfo] = useState<inWarehouseType | null>(null);
  const inWhVerifyDataList = Form.useWatch("inWhVerifyDataList", form);

  const search = async () => {
    const res = await inWhVerifyData({id: currentRow?.id});
    setInfo(res || {});
    if (res?.inWhVerifyDataList?.length > 0) {
      form.setFieldsValue({
        inWhVerifyDataList: res?.inWhVerifyDataList?.map((v: any) => ({
          ...v,
          isDefault: true
        }))
      });
    }
  }

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      orderId: info?.orderId,
      feeWeight: res?.feeWeight,
      feeVol: res?.feeVol,
      deleteIds: info?.inWhVerifyDataList?.filter((v: any) => !res?.inWhVerifyDataList?.some((s: any) => s?.id === v?.id))?.map((v: any) => v?.id),
      inWhDataList: res?.inWhVerifyDataList?.map((v: any) => ({
        id: v?.id,
        length: v?.length,
        width: v?.width,
        height: v?.height,
        pieces: v?.pieces,
        weight: v?.weight,
        vol: v?.vol
      }))
    });
  }

  useEffect(() => {
    if (currentRow?.id) {
      search();
    }
  }, [currentRow?.id]);

  useEffect(() => {
    if (inWhVerifyDataList?.length > 0 && !isEmptyObj(info)) {
      calcInWhVerifyData({
        inWhDataList: inWhVerifyDataList.map((v: any) => ({
          length: v?.length,
          width: v?.width,
          height: v?.height,
          pieces: v?.pieces,
          weight: v?.weight,
        })),
        leftWeightRatio: info?.leftWeightRatio,
        rightWeightRatio: info?.rightWeightRatio,
        minTakeCbm: info?.minTakeCbm,
        minTakeKgs: info?.minTakeKgs
      }).then(
        res => {
          if (res) {
            form.setFieldsValue({
              feeVol: res?.feeVol,
              feeWeight: res?.feeWeight,
              inWhVerifyDataList: inWhVerifyDataList?.map((v: any, index: number) => ({
                ...v,
                vol: res?.vols?.[index]
              })),
              totalWeight: inWhVerifyDataList?.reduce((p: number, v: {weight: number}) => {
                return  p + (v?.weight || 0);
              }, 0),
              totalVol: res?.vols?.reduce((p: number, v: number) => {
                return  p + (v || 0);
              }, 0)
            });
          }
        }
      )
    }
  }, [JSON.stringify(inWhVerifyDataList), JSON.stringify(info)])

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      maskClosable={false}
      width="1400px"
    >
      <Form form={form} className="modal-form-padding">
        <div className="xl-self-table">
          <div className="thead">
            <Row className="tr">
              <Col span={4}>
                <div className="th">箱数</div>
              </Col>
              <Col span={4}>
                <div className="th">长/CM</div>
              </Col>
              <Col span={4}>
                <div className="th">宽/CM</div>
              </Col>
              <Col span={4}>
                <div className="th">高/CM</div>
              </Col>
              <Col span={3}>
                <div className="th">对应重量</div>
              </Col>
              <Col span={3}>
                <div className="th">对应体积</div>
              </Col>
              <Col span={2}>
                <div className="th">操作</div>
              </Col>
            </Row>
          </div>
          <div className="tbody">
            <Form.List name="inWhVerifyDataList">
              {(fields, { add, remove }) => (
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {fields.map((field, fieldIndex) => (
                    <Row className="tr" key={field.name}>
                      <Item noStyle hidden name={[field.name, 'id']}>
                        <Input />
                      </Item>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'pieces']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'length']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'width']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'height']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={3}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'weight']} rules={rules}>
                            <InputNumber style={{width: 130}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={3}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'vol']} rules={rules}>
                            <InputNumber disabled style={{width: 130}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={2}>
                        <div className="td">
                          <Space>
                            <Button type="primary" onClick={() => add({isDefault: false})} icon={<PlusOutlined/>}></Button>
                            {fieldIndex > 0 && <Button type="primary" onClick={() => remove(field.name)} icon={<MinusOutlined/>}></Button>}
                          </Space>
                        </div>
                      </Col>
                    </Row>
                  ))}
                </div>
              )}
            </Form.List>
          </div>
        </div>
        <Row style={{marginTop: 30}}>
          <Col span={6}>
            <Item name="feeVol" label="计费体积">
              <InputNumber style={{width: 200}} disabled />
            </Item>
          </Col>
          <Col span={6}>
            <Item name="feeWeight" label=" 计费重量">
              <InputNumber style={{width: 200}} disabled />
            </Item>
          </Col>
          <Col span={6}>
            <Item name="totalWeight" label="总重量">
              <InputNumber style={{width: 200}} disabled />
            </Item>
          </Col>
          <Col span={6}>
            <Item name="totalVol" label="总体积">
              <InputNumber style={{width: 200}} disabled />
            </Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}
export default WarehouseEntryExport;